let app = getApp();
let userId;
let storeId;
let merchantId;
let member;
let shuju;
let url = app.globalData.url;
let jiu;
let arr;
const defHeaders = {
  'Content-Type': 'application/json;charset=UTF-8',
  'Accept': 'application/json',
};
Page({
  data: {
    list3: [],
    input_value: '',
    showOrHidden: false,//是否会员隐藏支付按钮
    merchantName: '',
    merchantName: '',
    bkg: '',
    display: 'block',
    load: "none",
    cun_dis:"",
    quan_list: [],
    quan: ""
  },



  onLoad(query) {
    wx.showLoading({
      title: '正在加载',
    })
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);

    var that = this;
    var getlist3


    try {
      wx.getStorage({
        key: 'storeId',
        success: function (res) {
          storeId = res.data.storeId;
          // my.alert({ content: '获取成功：' + res.data.storeId});
          console.log("scavening-------GGGGGGGGGGGGG-----------------storeId" + storeId)

          that.merchantName(storeId);
        },
        fail: function (res) {
          // my.alert({ content: res.errorMessage });
        }
      });

    } catch (e) {
      console.log("scavening-------------------GGGGGGGGGGGGG-----------------没存storeId")
      if (storeId == '' || typeof (storeId) == "undefined") {

        // storeId = ''
        storeId = '265106126102700032'
      }

    }



    try {

      wx.getStorage({
        key: 'merchantId',
        success: function (res) {
          merchantId = res.data.merchantId;

          //获取卡券列表
          wx.request({
            url: url + "/card/getDepostiList.do",
            method: 'get',
            data: {
              merchantId: merchantId,
              storeId: storeId,

            },
            headers: {
              defHeaders,
            },
            dataType: 'json',
            success: function (res) {
              console.log(res)

              shuju = res.data.body;
              // this.handleGetAllAccountInfo();

              getlist3 = res.data.body;
              jiu = res.data.body;
              var nArr = [];
              var obj = { "charge_icon": '../../pages/images/charge2.png', "gift_icon": '../../pages/images/gift2.png' }
              for (var i in jiu) {
                if (jiu[i].benefit == 0) {
                  jiu[i].amount1 = jiu[i].amount;
                  jiu[i].benefit1 = " ";
                  jiu[i].chong1 = " ";
                  nArr.push(jiu[i]);
                } else {
                  jiu[i].amount1 = jiu[i].amount;
                  jiu[i].benefit1 = "赠" + jiu[i].benefit + "元";
                  jiu[i].chong1 = "充" + jiu[i].amount + "赠" + jiu[i].benefit;
                  nArr.push(jiu[i]);

                }

              }
              let all = res.data.body[0].amount;
              let zeng = res.data.body[0].benefit;
              if (zeng == 0) {
                that.setData({
                  cun_dis: "none"
                })
              }
              let yu = all + zeng;
              that.setData({
                list3: nArr,
                isSelect: "0",
                input_value: all,
                all: all,
                money: zeng,
                yu: yu,
              });

              that.setData({
                display: "none",
              })
              wx.hideLoading()
            },
            fail: function (res) {
              // wx.alert({
              //   content: res,
              // });
              console.log("获取卡券列表eeeeeeeeeeeeeeeeeeeee" + res)
            },
            complete: function (res) {

            }
          });


          //  获得优惠券，判断是否有优惠券
          wx.request({
            url: url + '/marketing/getStoredValueMemberOrderList.do?',
            method: 'get',
            data: {
              merchantId: merchantId,
            },
            headers: {
              defHeaders,
            },
            dataType: 'json',
            success: function (res) {
              console.log("券")
              console.log(res)
              if (res.data.body == [] || res.data.body == "") {
                that.setData({
                  quan: "none"
                })
              } else {
                that.setData({
                  quan_list: res.data.body,
                })
              }



            },
            fail: function (res) {
              my.navigateTo({
                url: "../abnormal/abnormal"
              });
              setTimeout(() => {
                my.hideLoading({
                });
                that.setData({
                  display: "none",
                })
              }, 300);
            },
            complete: function (res) {
              // my.hideLoading();
            }
          });


          // my.alert({ content: '获取成功：' + res.data.merchantId });
        },
        fail: function (res) {
          // my.alert({ content: res.errorMessage });
        }
      });

    } catch (e) {
      console.log("scavenging-------------------GGGGGGGGGGGGG-----------------你没存merchantId")

    }









    var that = this;
    try {
      wx.getStorage({
        key: 'merchantName',
        success: function (res) {
          let merchantName = res.data.merchantName;

          that.setData({
            merchantName: merchantName,

          });
        },
        fail: function (res) {
          // my.alert({ content: res.errorMessage });
        }
      });
    } catch (e) {
      console.log("scavening-------------------GGGGGGGGGGGGG-----------------没存merchantName")
      if (merchantName == '' || typeof (merchantName) == "undefined") {
        merchantName = ''
      }
    }



  },


  //金额输入框监听
  input: function (e) {
    let benefit;
    let balance;
    let moneys;
    console.log("...........11111111111" + e.detail.value)
    var val = e.detail.value;
    var num = val.indexOf('.');
    if (num > 0) {
      num = parseInt(num) + 2;
      var len = val.length - 1;
      if (len > num) {
        wx.showModal({
          title: "请输入有效金额",
        });
        this.setData({
          input_value: "",
        })
        return false;
      }

    }
    // 得到输入的值
    console.log(4444444444444)
    moneys = e.detail.value;
    if (moneys == "") {
      moneys = 0;
      benefit = 0;
      balance = 0
    } else {
      for (let i = 0; i < jiu.length; i++) {
        if (moneys < jiu[0].amount) {
          moneys = moneys;
          benefit = 0;
          balance = moneys
        } else if (moneys >= jiu[i].amount) {
          //  最近支付钱数
          let amount = jiu[i].amount;
          console.log(amount)
          //  最近赠送的钱数
          benefit = jiu[i].benefit;
          console.log(benefit)
          // 存入会员余额
          balance = benefit + parseFloat(moneys);
          console.log(balance)
        }
      }
    }
    this.setData({
      input_value: e.detail.value,
      all: moneys,
      money: benefit,
      yu: balance
    })

  },

  //立即支付
  immediatePayment() {

    var that = this;
    that.setData({
      load: "block"
    })
    wx.showLoading({
      title: '等待付款',
    })
    //调用充值支付
    that.rechargeMethod();
  },


  //充值支付方法
  rechargeMethod: function () {
    var that = this;
    if (that.data.input_value > 0) {
      wx.getStorage({
        key: 'userId',
        success: function (res) {
          var userId = res.data.userId;
          wx.getStorage({
            key: 'openId',
            success: function (res) {
              var openId = userId + ',' + res.data.openId
              wx.getStorage({
                key: 'storeId',
                success: function (res) {
                  var storeId = res.data.storeId;
                  // 生成订单号
                  wx.request({
                    url: url + '/card/createWxPay.do',
                    method: 'get',
                    headers: {
                      'Content-Type': 'application/json;charset=UTF-8',
                      'Accept': 'application/json',
                    },
                    data: {
                      storeId: storeId,
                      totalAmount: that.data.input_value,
                      openId: openId,
                    },
                    dataType: 'json',
                    success: function (res) {
                      that.setData({
                        load: "none"
                      })
                      wx.hideLoading()
                      console.log("订单返回")
                      var appid = res.data.body.appId
                      console.log(res.data.body.paySign)
                      var paySign = res.data.body.paySign
                      console.log(res.data.body.nonceStr)
                      var nonceStr = res.data.body.nonceStr
                      console.log(res.data.body.packageStr)
                      var packageStr = res.data.body.packageStr
                      console.log(res.data.body.timeStamp)
                      var timeStamp = res.data.body.timeStamp
                      console.log(res)
                        var signType = res.data.body.signType
                      if (res.data.code == 1) {
                        // wx.request({
                        //   url: url + '/auth/getCxcSign.do',
                        //   method: 'get',
                        //   data: {
                        //     appid: "",
                        //     packageStr: packageStr,
                        //     nonceStr: nonceStr
                        //   },
                        //   headers: {
                        //     'Content-Type': 'application/json;charset=UTF-8',
                        //     'Accept': 'application/json',
                        //   },
                        //   dataType: 'json',
                        //   success: function (res) {
                        //     console.log("签名")
                        //     console.log(res)
                        //4.唤起支付
                        wx.requestPayment({
                          timeStamp: timeStamp,
                          nonceStr: nonceStr,
                          package: packageStr,
                            signType: signType,
                          paySign: paySign,
                          success: (res) => {
                            console.log(res)
                            that.setData({
                              membersavings_dis: "none",
                              key_dis: "block",
                              first: "0",
                              no_btn: false
                            })
                            wx.switchTab({
                              url: '../membershipCard/membershipCard',
                            })
                              wx.setStorage({
                                  key: 'type',
                                  data: {
                                      type: 2,
                                  },
                              })
                          },
                          fail: (res) => {
                            console.log(res)
                          }
                        })

                        //   }
                        // })



                      } else if (res.data.code == 2) {
                        //  my.alert({
                        //    title:"支付成功",
                        //   content: res.data.body.totalAmount
                        // });
                        that.tanchu();
                      }


                    },
                    fail: function (res) {
                      console.log(res)
                    },
                    complete: function (res) {


                    }
                  })
                }
              })
            }
          })
        }
      })
    } else {
      wx.showModal({ title: "请输入充值金额" })
      that.setData({
        load: "none"
      })
      wx.hideLoading()
    }
  },
  onReady() {
    // 页面加载完成

  },


  onShow() {

    this.onLoad();//刷新页面

  },


  //优惠券点击事件
  handleItemClick(ev) {

    var that = this;
    var all = ev.currentTarget.dataset.amount;
    var index = ev.currentTarget.dataset.index;
    console.log(index);
    // 得到赠送的钱数
    var zeng = ev.currentTarget.dataset.benefit;
    if (zeng > 0) {
      that.setData({
        cun_dis: "block"
      })
    } else {
      that.setData({
        cun_dis: "none"
      })
    }
    var yu = all + zeng;
    that.setData({
      isSelect: index,
      input_value: all,
      bkg: "#c0c0c0",
      all: all,
      money: zeng,
      yu: yu
    });
    setTimeout(function () {
      that.setData({
        bkg: ""
      });
    }, 300);
  },

  //获取门店名字
  merchantName(storeId) {
    var areMembers;
    var that = this;

    wx.request({
      url: url + '/store/getByStoreId.do',
      method: 'GET',
      headers: {
        defHeaders,
      },

      data: {
        storeId: storeId,
      },
      dataType: 'json',
      success: function (res) {
        console.log("----------**************存储merchantName-------------------" + JSON.stringify(res.data))
        if (typeof (res.data.body) != "undefined") {

          that.setData({
            merchantName: res.data.body.name,

          });

          wx.setStorage({
            key: 'merchantName',
            data: {
              merchantName: res.data.body.name,
            },
            success: function () {
              console.log("**************存储merchantName-------------------" + JSON.stringify(res.data.body.name))
            }
          });
          console.log("**************存储merchantName后后--------------------" + JSON.stringify(res.data.body.name))
        } else if (typeof (res.data.body) == "undefined") {

          console.log("**************else------------存储merchantName--------------------" + JSON.stringify(res.data.body))
          //不是会员
          wx.setStorage({
            key: 'member',
            data: {
              merchantName: res.data.body.name,
            },
            success: function () {
              // aremerchantNameMembers = false;
            }
          });
        }

      },
      fail: function (res) {
        console.log(res)
        return '请求商户失败'
      },
      complete: function (res) {
        // my.hideLoading();
      }
    })


  },


  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
    console.log("&&&&&&&&&&&&&&&-----------储值页面关闭-------------->>>>>>>>>>>>>>")
    // my.clearStorageSync()
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    // 页面被拉到底部
  },
});